package com.example.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;


import java.util.Random;

@Aspect
@Component
public class orderserviceaspect {

    private final Random random = new Random();

    // 1. 前置增强
    @Before("execution(* com.example.service.orderservice.*(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强 → 方法: " + joinPoint.getSignature().getName());
    }

    // 2. 后置增强
    @AfterReturning("execution(* com.example.service.orderservice.add(..)) || " +
            "execution(* com.example.service.orderservice.delete(..))")
    public void afterReturningAdvice(JoinPoint joinPoint) {
        System.out.println("bye, 我是一个后置增强 → 方法: " + joinPoint.getSignature().getName());
    }

    // 3, 4, 5.获取返回值 + 计算耗时 + 权限控制
    @Around("execution(* com.example.service.orderservice.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();

        // 5. 权限检查（仅对 add 和 delete）
        if ("add".equals(methodName) || "delete".equals(methodName)) {
            int permission = random.nextInt(2); // 0=有权限, 1=无权限
            if (permission == 1) {
                System.out.println("权限不足！禁止执行方法: " + methodName);
                return null; // 终止方法执行
            } else {
                System.out.println("权限校验通过 → 方法: " + methodName);
            }
        }

        // 4. 计算执行时间
        long start = System.currentTimeMillis();

        // 执行原方法并获取返回值
        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();
        System.out.println("方法执行耗时: " + (end - start) + " ms");

        // 3. 输出返回值
        if (result != null) {
            System.out.println("方法返回值: " + result);
        }

        return result;
    }
}